<template>
  <div class="map-container">
    <div ref="mapRef" class="map"></div>
    <div v-if="loading" class="loading-overlay">地图加载中...</div>
    <div v-if="error" class="error-message">{{ error }}</div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { Loader } from '@googlemaps/js-api-loader'

const props = defineProps({
  apiKey: {
    type: String,
    required: true
  },
  markersData: {
    type: Array,
    default: () => []
  },
  center: {
    type: Object,
    default: () => ({ lat: 39.9042, lng: 116.4074 }) // 默认北京中心点
  },
  zoom: {
    type: Number,
    default: 12
  }
})

const mapRef = ref(null)
const map = ref(null)
const loading = ref(true)
const error = ref(null)
const markers = ref([])

// 初始化地图
const initMap = async () => {
  try {
    const loader = new Loader({
      apiKey: props.apiKey,
      version: 'weekly',
      libraries: ['places']
    })

    console.log(loader);
    

    await loader.load()

    map.value = new google.maps.Map(mapRef.value, {
      center: props.center,
      zoom: props.zoom,
      disableDefaultUI: true, // 可选：禁用默认UI控件
      styles: [] // 可选：自定义地图样式
    })

    loading.value = false
    updateMarkers()
  } catch (err) {
    error.value = '地图加载失败: ' + err.message
    loading.value = false
    console.error('地图初始化错误:', err)
  }
}

// 更新标记点
const updateMarkers = () => {
  // 清除现有标记
  clearMarkers()
  
  if (!map.value || !props.markersData.length) return
  
  markers.value = props.markersData.map(markerData => {
    const marker = new google.maps.Marker({
      position: {
        lat: parseFloat(markerData.latitude),
        lng: parseFloat(markerData.longitude)
      },
      map: map.value,
      title: markerData.title || '位置点',
      icon: markerData.icon || null // 可以自定义图标
    })
    
    // 添加信息窗口
    if (markerData.info) {
      const infoWindow = new google.maps.InfoWindow({
        content: `
          <div class="info-window">
            <h3>${markerData.title || '位置信息'}</h3>
            <p>${markerData.info}</p>
            ${markerData.image ? `<img src="${markerData.image}" alt="${markerData.title}" width="150">` : ''}
          </div>
        `
      })
      
      marker.addListener('click', () => {
        infoWindow.open(map.value, marker)
      })
    }
    
    return marker
  })
  
  // 如果有标记点，调整视图以包含所有标记
  if (markers.value.length > 0) {
    const bounds = new google.maps.LatLngBounds()
    markers.value.forEach(marker => {
      bounds.extend(marker.getPosition())
    })
    map.value.fitBounds(bounds)
  }
}

// 清除所有标记
const clearMarkers = () => {
  markers.value.forEach(marker => {
    marker.setMap(null)
  })
  markers.value = []
}

// 监听数据变化
watch(() => props.markersData, updateMarkers, { deep: true })

onMounted(initMap)
</script>

<style scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.map {
  width: 100%;
  height: 100%;
  min-height: 400px;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.error-message {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  padding: 1rem;
  background: #ffebee;
  color: #c62828;
  z-index: 1000;
}
</style>